import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_im_demo/state/global_state.dart';
import 'package:provider/provider.dart';
import 'package:image_picker/image_picker.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

import '../const_value.dart';
import 'broadcast_list_page.dart';
import 'chat_list_page.dart';
import 'friend_list_page.dart';
import 'my_info_page.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _currentIndex = 0;

  PageController _pageController;

  @override
  void initState() {
    super.initState();
    _pageController = PageController(initialPage: 0);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: PageView.builder(
          controller: _pageController,
          onPageChanged: _onNavigationBarTap,
          itemBuilder: _itemBuild,
          itemCount: 3),
      bottomNavigationBar: BottomNavigationBar(
        items: [
          BottomNavigationBarItem(
              icon: Icon(FontAwesomeIcons.comment, size: iconSize + 2),
              activeIcon: Icon(FontAwesomeIcons.solidComment, size: iconSize + 2),
              title: Text("聊天")),
          BottomNavigationBarItem(
              icon: Icon(FontAwesomeIcons.addressBook, size: iconSize + 2),
              activeIcon: Icon(FontAwesomeIcons.solidAddressBook, size: iconSize + 2),
              title: Text("通讯录")),
          BottomNavigationBarItem(
              icon: Icon(FontAwesomeIcons.user, size: iconSize + 2),
              activeIcon: Icon(FontAwesomeIcons.solidUser, size: iconSize + 2),
              title: Text("我的")),
        ],
        backgroundColor: Colors.white,
        onTap: _onNavigationBarTap,
        currentIndex: _currentIndex,
        type: BottomNavigationBarType.fixed,
      ),
    );
  }

  Future<List<int>> selectImage() async {
    try {
      File imageFile = await ImagePicker.pickImage(source: ImageSource.gallery);
      if (imageFile != null) {
        return await imageFile.readAsBytes();
      }
    } catch (e) {
      print("error: ${e}");
    }
    return null;
  }

  void _onNavigationBarTap(int value) {
    setState(() {
      _currentIndex = value;
      _pageController.animateToPage(value,
          duration: Duration(milliseconds: 10), curve: Curves.ease);
    });
  }

  Widget _itemBuild(BuildContext context, int index) {
    switch (index) {
      case 0:
        return const ChatListPage();
      case 1:
        return const FriendListPage();
      case 2:
        return const MyInfoPage();
    }
  }
  
  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }
}
